﻿#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "quihelper.h"
#include "quihelperdata.h"
#include "settingdlg.h"
#include "jzcommand.h"
#include "msgdlg.h"
#include <QDesktopServices>
#include <QProcess>
#include "start.h"


MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    resize(1280, 800);
    this->setWindowFlags(Qt::FramelessWindowHint);//无边框设置
    this->setWindowTitle("金属探测终端");
    this->setObjectName("mainWindow");
    this->setStyleSheet("#mainWindow{border-image:url(:/image/bg4.png);}");

    arr << "" << "" << "" << "" << "";
    initDB();
    initDevice();
    initUI();
    initCom();
    getjiaoyanjilu();
    setjiaoyanjilu();

    m_threadSocket.setSocketConfigure(kanbanIP, 8023);

    // 测试第一次启动md11读取数据库表格，填写
    playWavFile(0);

    // UPC = "AS12212asfsdf11121233";
    // mTiaoma->setText(QString(tr("条码:") + "%1").arg(UPC));
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::initDevice()
{
    QSettings set(SettingDlg::ConfigFile, QSettings::IniFormat);
//    Start::getInstance().writeLog("[initDevice]" + SettingDlg::ConfigFile);
    mLinename = set.value("linename", "").toString();
    mSn = set.value("sn", "").toString();
    sensors = set.value("sensors", "10").toInt();
    accuracy = set.value("accuracy", "10").toInt();
    if (mSn.length() < 1) {
        //1656577643081 -- 毫秒
        mLinename = QString("Line_%1").arg(QDateTime::currentMSecsSinceEpoch());
        mSn = QUuid::createUuid().toString();
        mSn = mSn.mid(1, mSn.length() - 2);
        mSn = mSn.replace("-", "");
        set.setValue("sn", mSn);
        set.setValue("linename", mLinename);
        saveLinesn(mLinename, mSn);
    }
    Start::getInstance().strSn = mSn;

    //提取路数信息
    for(int i = 1; i <= 10; i++) {
        myMap.insert(i, set.value(QString::number(i), QString::number(i)).toInt());
    }

    bHasRFID = set.value("bHasRFID", "false").toBool();
    bHasXRay = set.value("bHasXRay", "false").toBool();
    bHasKanban = set.value("hasKanban", "false").toBool();
    kanbanIP = set.value("kanbanIP", "192.168.111.100").toString();
    bIs900N = set.value("bIs900N", "false").toBool();

    set.setValue("hasKanban", bHasKanban);
    set.setValue("kanbanIP", kanbanIP);
    set.setValue("bHasRFID", bHasRFID);
    set.setValue("bHasXRay", bHasXRay);//没有用
    set.setValue("bIs900N", bIs900N);

}

void MainWindow::initCom()
{
    comOk = false;
    jz_com = 0;
    accuracy_com = 0;
    saoma_com = 0;
    sleepTime = 10;
    receiveCount = 0;
    sendCount = 0;

    //读取检针机数据
    jz_timerRead = new QTimer(this);
    jz_timerRead->setInterval(100);
    connect(jz_timerRead, SIGNAL(timeout()), this, SLOT(jz_readData()));

    //读取灵敏度数据
    accuracy_timerRead = new QTimer(this);
    accuracy_timerRead->setInterval(100);
    connect(accuracy_timerRead, SIGNAL(timeout()), this, SLOT(accuracy_readData()));

    //读取扫码枪数据
    saoma_timerRead = new QTimer(this);
    saoma_timerRead->setInterval(100);
    connect(saoma_timerRead, SIGNAL(timeout()), this, SLOT(saoma_readData()));

    //每秒刷新断针列表和合格数
    timerUpdatedata = new QTimer(this);
    timerUpdatedata->setInterval(1000);
    connect(timerUpdatedata, SIGNAL(timeout()), this, SLOT(udateuibydb()));
    timerUpdatedata->start();

    //读取RFID数据 from DB
    timerReadRfidtable = new QTimer(this);
    timerReadRfidtable->setInterval(200);
    connect(timerReadRfidtable, SIGNAL(timeout()), this, SLOT(rfidtable_readData()));
    timerReadRfidtable->start();


    this->openSerialport();

    sendData(Jzcommand::writexulie(), true); //启动检针机

    //是否重置检针机合格数和金属数（是否需要插入hostory）
    if (db1.isOpen()) {
        QSqlQuery query1(db1);
        QString riqi = QDateTime::currentDateTime().toString("yyyy-MM-dd");
        QString sql = QString("select id from hostorydata where sn='%1' and riqi='%2'").arg(mSn, riqi);
        query1.exec(sql);

        if(!query1.next()) {
            QString uuid = QUuid::createUuid().toString();
            uuid = uuid.mid(1, uuid.length() - 2);
            uuid = uuid.replace("-", "");
            sql = QString("insert into hostorydata(id,riqi,sn) values ('%1','%2','%3') ").arg(uuid, riqi, mSn);
            query1.exec(sql);

            query1.exec("update jiaoyanshezhi set zt=0");
            sendData(Jzcommand::getczcmd(hege, chupan), true); //每日仅重置1次
        }
    }


    //延时1000毫秒执行load函数 -- 启动时呼叫检针机--请求数据
    QTimer::singleShot(1000, this, SLOT(calljzj()));
}

void MainWindow::calljzj()
{
    sendData(Jzcommand::calljzj(), true);
}

void MainWindow::initUI()
{
    int w0 = 1024; //ui screentshoot 坐标参照图
    int h0 = 768;

    int W, H;
    W = this->width();
    H = this->height();

    double wx = W * 1.0/ w0;//x 修正系数
    double hx = H * 1.0/ h0;//y 修正系数

    TEXTVIEW_INFO t;
    BMPBUTTON_INFO b;

    t.revert();
    mWebview = new TextView(this);
    mWebview->setGeometry(0, 0, 200 * wx, 70 * hx);
    mWebview->setUI(t);

    t.revert();
    mAccuracy = new TextView(this);
    mAccuracy->setGeometry(W - 680 * wx, 10, 300 * wx, 70 * hx);
    t.fontSize = 28;
    t.fontWeight = 700;
    t.txtColor = QColor(255, 255, 255);
    t.flag = Qt::AlignLeft | Qt::AlignVCenter;
    mAccuracy->setUI(t);
    mAccuracy->setText(QString("%1").arg(accuracy));

    t.revert();
    mTiaoma = new TextView(this);
    mTiaoma->setGeometry(W - 600 * wx, 10, 420 * wx, 70 * hx);
    t.fontSize = 24;
    t.fontWeight = 700;
    t.txtColor = QColor(255, 255, 255);
    t.flag = Qt::AlignLeft | Qt::AlignVCenter;
    mTiaoma->setUI(t);
    mTiaoma->setText(tr("条码:"));

    t.revert();
    mDingdan = new TextView(this);
    mDingdan->setGeometry(W - 250 * wx, 10, 250 * wx, 70 * hx);
    t.fontSize = 24;
    t.fontWeight = 700;
    t.txtColor = QColor(255, 255, 255);
    mDingdan->setUI(t);
    //mDingdan->setText(tr("订单: "));

    t.revert();
    mChupan_t = new TextView(this);
    mChupan_t->setGeometry(360 * wx, 376 * hx, 180 * wx, 44 * hx);
    t.fontSize = 16;
    t.fontWeight = 700;
    t.txtColor = QColor(255, 255, 255);
    mChupan_t->setUI(t);
    mChupan_t->setText(tr("MD检测不合格数"));

    t.revert();
    mChupan = new TextView(this);
    mChupan->setGeometry(315 * wx, 439 * hx, 270 * wx, 59 * hx);
    t.fontSize = 24;
    t.fontWeight = 700;
    t.txtColor = QColor(0, 0, 0);
    t.backgroundColor = QColor(255, 0, 0);
    mChupan->setUI(t);
    mChupan->setText("11");

    t.revert();
    mXrayTobeConfirm_t = new TextView(this);
    mXrayTobeConfirm_t->setGeometry(360 * wx, 529 * hx, 180 * wx, 45 * hx);
    t.fontSize = 16;
    t.fontWeight = 700;
    t.txtColor = QColor(255, 255, 255);
    mXrayTobeConfirm_t->setUI(t);
    mXrayTobeConfirm_t->setText(tr("X-Ray待确认数"));

    t.revert();
    mXrayTobeConfirm = new TextView(this);
    mXrayTobeConfirm->setGeometry(315 * wx, 584 * hx, 270 * wx, 59 * hx);
    t.fontSize = 24;
    t.fontWeight = 700;
    t.txtColor = QColor(0, 0, 0);
    t.backgroundColor = QColor(255,255,0);
    mXrayTobeConfirm->setUI(t);
    mXrayTobeConfirm->setText("0");

    t.revert();
    mHgs_t = new TextView(this);
    mHgs_t->setGeometry(760 * wx, 376 * hx, 162 * wx, 45 * hx);
    t.fontSize = 16;
    t.fontWeight = 700;
    t.txtColor = QColor(255, 255, 255);
    mHgs_t->setUI(t);
    mHgs_t->setText(tr("总合格数"));

    t.revert();
    mHgs = new TextView(this);
    mHgs->setGeometry(700 * wx, 439 * hx, 270 * wx, 59 * hx);
    t.fontSize = 24;
    t.fontWeight = 700;
    t.txtColor = QColor(0, 0, 0);
    t.backgroundColor = QColor(0, 255, 0);
    mHgs->setUI(t);

    t.revert();
    mXrayFail_t = new TextView(this);
    mXrayFail_t->setGeometry(760 * wx, 529 * hx, 161 * wx, 59 * hx);
    t.fontSize = 16;
    t.fontWeight = 700;
    t.txtColor = QColor(255, 255, 255);
    mXrayFail_t->setUI(t);
    mXrayFail_t->setText(tr("X-Ray判定不合格数"));

    t.revert();
    mXrayFail = new TextView(this);
    mXrayFail->setGeometry(700 * wx, 584 * hx, 270 * wx, 59 * hx);
    t.fontSize = 24;
    t.fontWeight = 700;
    t.txtColor = QColor(0, 0, 0);
    t.backgroundColor = QColor(255,0,0);
    mXrayFail->setUI(t);

    t.revert();
    mJy00 = new TextView(this);
    mJy00->setGeometry(38 * wx, 535 * hx, 45 * hx, 45 * hx);
    t.backgroundBmp = QString("c3");
    mJy00->setUI(t);

    t.revert();
    mJy01 = new TextView(this);
    mJy01->setGeometry(140 * wx, 529 * hx, 108 * wx, 48 * hx);
    t.fontSize = 16;
    t.fontWeight = 700;
    t.txtColor = QColor(255, 255, 255);
    mJy01->setUI(t);
    mJy01->setText(tr("检测"));

    t.revert();
    mJy10 = new TextView(this);
    mJy10->setGeometry(16 * wx, 578 * hx, 81 * wx, 45 * hx);
    t.fontSize = 16;
    t.fontWeight = 700;
    t.txtColor = QColor(255, 255, 255);
    mJy10->setUI(t);
    mJy10->setText(tr("检出"));

    t.revert();
    mJy11 = new TextView(this);
    mJy11->setGeometry(168 * wx, 578 * hx, 48 * wx, 43 * hx);
    t.fontSize = 16;
    t.fontWeight = 700;
    t.txtColor = QColor(255, 255, 255);
    mJy11->setUI(t);
    mJy11->setText("0");

    t.revert();
    mJy20 = new TextView(this);
    mJy20->setGeometry(16 * wx,  625 * hx, 81 * wx, 45 * hx);
    t.fontSize = 16;
    t.fontWeight = 700;
    t.txtColor = QColor(255, 255, 255);
    mJy20->setUI(t);
    mJy20->setText(tr("漏检"));

    t.revert();
    mJy21 = new TextView(this);
    mJy21->setGeometry(168 * wx,  625 * hx, 48 * wx, 43 * hx);
    t.fontSize = 16;
    t.fontWeight = 700;
    t.txtColor = QColor(255, 255, 255);
    mJy21->setUI(t);
    mJy21->setText("0");

    t.revert();
    button11 = new TextView(this);
    button11->setGeometry(20 * wx,  370 * hx, 39 * hx, 39 * hx);
    t.backgroundBmp = QString("b2");
    t.text = QString("1");
    button11->setUI(t);

    t.revert();
    button12 = new TextView(this);
    button12->setGeometry(20 * wx,  410 * hx, 39 * hx, 39 * hx);
    t.backgroundBmp = QString("b2");
    t.text = QString("2");
    button12->setUI(t);

    t.revert();
    button13 = new TextView(this);
    button13->setGeometry(20 * wx,  450 * hx, 39 * hx, 39 * hx);
    t.backgroundBmp = QString("b2");
    t.text = QString("3");
    button13->setUI(t);

    t.revert();
    button14 = new TextView(this);
    button14->setGeometry(20 * wx,  491 * hx, 39 * hx, 39 * hx);
    t.backgroundBmp = QString("b1");
    t.text = QString("4");
    button14->setUI(t);

    button11->setVisible(false);
    button12->setVisible(false);
    button13->setVisible(false);
    button14->setVisible(false);

    t.revert();
    label29 = new TextView(this);
    label29->setGeometry(83 * wx,  376 * hx, 100 * wx, 35 * hx);
    t.fontSize = 16;
    t.fontWeight = 700;
    t.flag = Qt::AlignLeft|Qt::AlignHCenter;
    t.txtColor = QColor(255, 255, 255);
    label29->setUI(t);

    t.revert();
    label28 = new TextView(this);
    label28->setGeometry(83 * wx,  417 * hx, 100 * wx, 35 * hx);
    t.fontSize = 16;
    t.fontWeight = 700;
    t.flag = Qt::AlignLeft|Qt::AlignHCenter;
    t.txtColor = QColor(255, 255, 255);
    label28->setUI(t);

    t.revert();
    label27 = new TextView(this);
    label27->setGeometry(83 * wx,  459 * hx, 100 * wx, 35 * hx);
    t.fontSize = 16;
    t.fontWeight = 700;
    t.flag = Qt::AlignLeft|Qt::AlignHCenter;
    t.txtColor = QColor(255, 255, 255);
    label27->setUI(t);

    t.revert();
    label26 = new TextView(this);
    label26->setGeometry(83 * wx,  497 * hx, 100 * wx, 35 * hx);
    t.fontSize = 16;
    t.fontWeight = 700;
    t.flag = Qt::AlignLeft|Qt::AlignHCenter;
    t.txtColor = QColor(255, 255, 255);
    label26->setUI(t);

    t.revert();
    mZt = new TextView(this);
    mZt->setGeometry(944 * wx, 689 * hx, 62 * hx, 62 * hx);
    t.backgroundBmp = QString("zt1");
    mZt->setUI(t);

    b.revert();
    mJiaozhen = new BmpButton(this);
    mJiaozhen->setGeometry(4 * wx, 689 * hx, 180 * wx, 64 * hx);
    b.bmpPath = QString("bt1");
    b.bmpPathPressed = QString("bt3");
    b.bmpPathX = QString("");
    b.text = tr("校正");
    b.fontWeight = 700;
    b.txtColor = QColor(255, 255, 255);
    mJiaozhen->setUI(b);

    b.revert();
    mZhengchang = new BmpButton(this);
    mZhengchang->setGeometry(189 * wx, 689 * hx, 180 * wx, 64 * hx);
    b.bmpPath = QString("bt3");
    b.bmpPathPressed = QString("bt1");
    b.bmpPathX = QString("");
    b.text = tr("正常");
    b.fontWeight = 700;
    b.txtColor = QColor(255, 255, 255);
    mZhengchang->setUI(b);

    b.revert();
    mLuru = new BmpButton(this);
    mLuru->setGeometry(374 * wx, 689 * hx, 180 * wx, 64 * hx);
    b.bmpPath = QString("bt1");
    b.bmpPathPressed = QString("bt3");
    b.bmpPathX = QString("");
    b.text = tr("录入");
    b.fontWeight = 700;
    b.txtColor = QColor(255, 255, 255);
    mLuru->setUI(b);

    b.revert();
    mPrint = new BmpButton(this);
    mPrint->setGeometry(557 * wx, 689 * hx, 180 * wx, 64 * hx);
    b.bmpPath = QString("bt1");
    b.bmpPathPressed = QString("bt3");
    b.bmpPathX = QString("");
    b.text = tr("打印");
    b.fontWeight = 700;
    b.txtColor = QColor(255, 255, 255);
    mPrint->setUI(b);

    mLuru->setVisible(false);
    mPrint->setVisible(false);

    b.revert();
    mSetting = new BmpButton(this);
    //    mSetting->setGeometry(741 * wx, 689 * hx, 180 * wx, 64 * hx);
    mSetting->setGeometry(557 * wx, 689 * hx, 180 * wx, 64 * hx);
    b.bmpPath = QString("bt1");
    b.bmpPathPressed = QString("bt3");
    b.bmpPathX = QString("");
    b.text = tr("设置");
    b.fontWeight = 700;
    b.txtColor = QColor(255, 255, 255);
    mSetting->setUI(b);

    b.revert();
    mExit = new BmpButton(this);
    //    mExit->setGeometry(929 * wx, 683 * hx, 70 * wx, 70 * hx);
    mExit->setGeometry(741 * wx, 689 * hx, 180 * wx, 64 * hx);
    b.bmpPath = QString("bt1");
    b.bmpPathPressed = QString("bt3");
    b.bmpPathX = QString("");
    b.text = tr("关机");
    b.fontWeight = 700;
    b.txtColor = QColor(255, 255, 255);
    //    b.icon = 0xf011;
    //    b.fontSize = 70;
    //    b.txtColor = QColor(255, 255, 255);
    //    b.txtColorPressed = QColor(255, 255, 0);
    mExit->setUI(b);

    mChupan->setText("0");
    mXrayTobeConfirm->setText("0");
    mHgs->setText("0");
    mXrayFail->setText("0");

    initListview2();

    fg1 = new QWidget(this);
    fg1->setGeometry(2*wx, 361* hx, 248*wx, 315* hx);
    fg1->setStyleSheet( "background:#BB000000;" );

    fg3 = new QWidget(this);
    fg3->setGeometry(260 * wx, 361* hx, 770*wx, 315* hx);
    fg3->setStyleSheet( "background:#BB000000;" );

    fg1->setVisible(false);
    fg3->setVisible(false);

    setSlot();
}

void MainWindow::initListview2()
{
    int w0 = 1024; //ui screentshoot 坐标参照图
    int h0 = 768;

    int W, H;
    W = this->width();
    H = this->height();

    double hx = H * 1.0/ h0;//y 修正系数

    tableWidget2 = new QTableWidget(this);
    tableWidget2->setGeometry(8, 88 * hx, W-16, 263 * hx);

    QFont font0 = tableWidget2->horizontalHeader()->font();
    font0.setBold(true);
    font0.setPointSize(14);
    tableWidget2->horizontalHeader()->setFont(font0);
    tableWidget2->setFont(font0);
    tableWidget2->setEditTriggers(QAbstractItemView::NoEditTriggers);//禁止编辑
    tableWidget2->horizontalHeader()->setStretchLastSection(true); //行头自适应表格
    tableWidget2->setSelectionMode(QAbstractItemView::NoSelection); //不选
    tableWidget2->setSelectionBehavior(QAbstractItemView::SelectRows); //整行选中的方式
    tableWidget2->setAlternatingRowColors(true);
    tableWidget2->verticalHeader()->setVisible(false);
    tableWidget2->horizontalHeader()->setHighlightSections(false);

    //设置表头
    tableWidget2->horizontalHeader()->setStyleSheet("QHeaderView::section{height:50px; background-color: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 #0973AB,stop:1 #098DCE);color: #ABD6FF;padding-left: 4px;border: 1px solid #383838;}");
    tableWidget2->verticalHeader()->setDefaultSectionSize(55);   //设置一行默认高度
    tableWidget2->verticalScrollBar()->setStyleSheet("QScrollBar{background-color:rgb(1, 137, 255); width:10px;}"
                                                     "QScrollBar::handle{background-color:rgb(1, 137, 255); border:2px solid transparent; border-radius:5px;}"
                                                     "QScrollBar::handle:hover{background-color:rgb(1, 137, 255);}"
                                                     "QScrollBar::sub-line{background:transparent;}"
                                                     "QScrollBar::add-line{background:transparent;}");

    //一定要在最后设置，否则设置列宽在ubuntu设备上不起作用。
    //设置列数和列宽
    int width = W-16;
    tableWidget2->setColumnCount(6);
    tableWidget2->setColumnWidth(0, width * 0.05);  //No
    tableWidget2->setColumnWidth(1, width * 0.30);  //UPC
    tableWidget2->setColumnWidth(2, width * 0.10);  //灵敏度
    tableWidget2->setColumnWidth(3, width * 0.30);  //时间
    tableWidget2->setColumnWidth(4, width * 0.12);  //MD状态
    tableWidget2->setColumnWidth(5, width * 0.12);  //XRay状态

    QStringList headText;
    headText << tr("NO") << tr("UPC") << tr("灵敏度") << tr("时间") << tr("MD结果") << tr("XRay结果");
    tableWidget2->setHorizontalHeaderLabels(headText);

}

void MainWindow::initJiaoZhengListview()
{
    if (tableWidget3 == NULL) {
        int w0 = 1024; //ui screentshoot 坐标参照图
        int h0 = 768;

        int W, H;
        W = this->width();
        H = this->height();

        double hx = H * 1.0/ h0;//y 修正系数

        tableWidget3 = new QTableWidget(this);
        tableWidget3->setGeometry(312 * hx, 364 * hx, 910 * hx, 315 * hx);
        QFont font0 = tableWidget3->horizontalHeader()->font();
        font0.setBold(true);
        font0.setPointSize(18);
        tableWidget3->horizontalHeader()->setFont(font0);
        tableWidget3->setFont(font0);
        tableWidget3->setEditTriggers(QAbstractItemView::NoEditTriggers);//禁止编辑
        tableWidget3->horizontalHeader()->setStretchLastSection(true); //行头自适应表格
        tableWidget3->setSelectionMode(QAbstractItemView::NoSelection); //不选
        tableWidget3->setSelectionBehavior(QAbstractItemView::SelectRows); //整行选中的方式
        tableWidget3->setAlternatingRowColors(true);
        tableWidget3->verticalHeader()->setVisible(false);
        tableWidget3->horizontalHeader()->setHighlightSections(false);

        //设置表头
        tableWidget3->horizontalHeader()->setStyleSheet("QHeaderView::section{height:50px; background-color: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 #0973AB,stop:1 #098DCE);color: #ABD6FF;padding-left: 4px;border: 1px solid #383838;}");
        tableWidget3->verticalHeader()->setDefaultSectionSize(35);   //设置一行默认高度
        tableWidget3->verticalScrollBar()->setStyleSheet("QScrollBar{background-color:rgb(1, 137, 255); width:10px;}"
                                                         "QScrollBar::handle{background-color:rgb(1, 137, 255); border:2px solid                    transparent; border-radius:5px;}"
                                                         "QScrollBar::handle:hover{background-color:rgb(1, 137, 255);}"
                                                         "QScrollBar::sub-line{background:transparent;}"
                                                         "QScrollBar::add-line{background:transparent;}");

        //一定要在最后设置，否则设置列宽在ubuntu设备上不起作用。
        //设置列数和列宽
        int width = 760 * hx;
        tableWidget3->setColumnCount(4);
        tableWidget3->setColumnWidth(0, width * 0.15);   //通道
        tableWidget3->setColumnWidth(1, width * 0.15);   //灵敏度
        tableWidget3->setColumnWidth(2, width * 0.55);   //时间
        tableWidget3->setColumnWidth(3, width * 0.15);   //状态

        QStringList headText;
        headText << tr("通道") << tr("灵敏度") << tr("时间") << tr("状态");
        tableWidget3->setHorizontalHeaderLabels(headText);
    }

    tableWidget3->setVisible(true);

    getData23();
}

void MainWindow::playWavFile(int iType) {
    if(iType == 0)
        effect->setSource(QUrl::fromLocalFile("scanok.wav"));
    else
        effect->setSource(QUrl::fromLocalFile("scanerr.wav"));
    //循环播放
    //effect->setLoopCount(QSoundEffect::Infinite);
    //设置音量，0-1
    effect->setVolume(0.9f);    // 不能设置为1.0，否则没有声音
    effect->play();
}

void MainWindow::setSlot()
{
    QObject::connect(mJiaozhen, SIGNAL(clicked()), this, SLOT(onJiaozhen()));
    QObject::connect(mZhengchang, SIGNAL(clicked()), this, SLOT(onZhengchang()));
    QObject::connect(mSetting, SIGNAL(clicked()), this, SLOT(onSetting()));
    QObject::connect(mExit, SIGNAL(clicked()), this, SLOT(onExit()));
}

void MainWindow::setjiaoyandetails()
{
    try {
        JZ_UUID = QUuid::createUuid().toString();
        //去掉前后{}
        if (JZ_UUID.startsWith("{") && JZ_UUID.endsWith("}")) {
            JZ_UUID = JZ_UUID.mid(1, JZ_UUID.length() - 2);
        }
        if (db1.isOpen()) {
            for (int i = 1; i <= sensors; i++) {
                QString sql = QString("INSERT INTO `jiaoyandetails`(`passageway`, `guid`) VALUES (%1, '%2')")
                        .arg(QString::number(i), JZ_UUID);
                QSqlQuery query(db1);
                query.exec(sql);
            }
        }
    } catch(const char *error) {
        qDebug() << "Caught exception: " << error;
    }
}

void MainWindow::onJiaozhen()
{
    if (model == 0) {
        mJiaozhen->setbmpPath("bt3", "bt1");
        mZhengchang->setbmpPath("bt1", "bt3");
    } else if (model == 1) {
        mJiaozhen->setbmpPath("bt3", "bt1");
        mZhengchang->setbmpPath("bt1", "bt3");
        mZhengchang->setText(tr("正常"));
    }

    model = 4;  //校正模式
    setjiaoyandetails();
    initJiaoZhengListview();
    mJy11->setText("0");
    mJy21->setText("0");

//    fg1->setVisible(false);
//    fg3->setVisible(true);
}

void MainWindow::onZhengchang()
{
    QString riqi = QDateTime::currentDateTime().toString("yyyy-MM-dd");
    QString shijian=  QDateTime::currentDateTime().toString("HH:mm:ss");

//    fg1->setVisible(true);
//    fg3->setVisible(false);

    if (model == 0) {
        model = 1;
        mZhengchang->setbmpPath("bt1", "bt3");
        mZhengchang->setText(tr("暂停"), true);

    } else if (model == 1) {
        model = 0;
        mZhengchang->setbmpPath("bt3", "bt1");
        mZhengchang->setText(tr("正常"), true);
        sendData(Jzcommand::getczcmd(hege, chupan), true);
    } else if (model == 4) {
        model = 0;
        mJiaozhen->setbmpPath("bt1", "bt3");
        mZhengchang->setbmpPath("bt3", "bt1");

        if (tableWidget3 != NULL) {
            tableWidget3->setVisible(false);
        }

        //取全部行的状态，如果都是OK，则校正完成
        int k = 0;
        if (mJy11->getText() != "0" || mJy21->getText() != "0") {
            if (mJy21->getText() != "0")
                k = 1;
            QString sql = QString("insert into jiaoyaninfo(shijian,riqi,bangjianchu,bangloujian,jieguo,sn,accuracy) "
                                  "values (date_format(now(),'%H:%i:%S'),'%1','%2','%3','%4','%5','%6')")
                    .arg(riqi, mJy11->getText(), mJy21->getText(), QString("%1").arg(k), mSn, QString("%1").arg(accuracy));
            sqlexecute(sql, 0);
            sql = QString("update jiaoyanshezhi set zt='1' where id=(select id "
                          "from (select * from jiaoyanshezhi where sn='%1' and starttime<'%2' order by starttime desc limit 1)as dd) ").arg(mSn, shijian);
            sqlexecute(sql, 0);
            l.append(Jiaoyan(shijian, QString("%1").arg(k)));
            setjiaoyanjilu();
            ll.clear();
            getjiaoyanshizhe();
            mJy11->setText("0");
            sendData(Jzcommand::getczcmd(hege, chupan), true);
        }
    }
}

void MainWindow::getjiaoyanjilu()
{
    l.clear();
    if (db1.isOpen()) {
        QString sql = QString("select jieguo,shijian from jiaoyaninfo where sn = '%1' and riqi='%2' and zt='0'").arg(mSn, QDateTime::currentDateTime().toString("yyyy-MM-dd"));
        QSqlQuery query(db1);
        query.exec(sql);
        while(query.next()) {
            l.append(Jiaoyan(query.value("shijian").toString(), query.value("jieguo").toString()));
        }
    }
}

void MainWindow::setjiaoyanjilu()
{
    if(l.size()<=0) {
        mJy21->setText("0");
        button11->setVisible(false);
        button12->setVisible(false);
        button13->setVisible(false);
        button14->setVisible(false);
    } else if(l.size()==1) {
        button11->setVisible(true);
        label29->setText(l[0].Sj);
        if (l[0].Jg=="1") {
            button11->setBackgroundBmp("b1");
            label29->setTextColor(QColor(255, 0, 0));
        }
        button12->setVisible(false);
        button13->setVisible(false);
        button14->setVisible(false);
    } else if(l.size()==2) {
        button11->setVisible(true);
        label29->setText(l[0].Sj);
        if (l[0].Jg == "1") {
            button11->setBackgroundBmp("b1");
            label29->setTextColor(QColor(255, 0, 0));
        }
        button12->setVisible(true);
        label28->setText(l[1].Sj);
        if (l[1].Jg == "1") {
            button12->setBackgroundBmp("b1");
            label28->setTextColor(QColor(255, 0, 0));
        }
        button13->setVisible(false);
        button14->setVisible(false);
    } else if (l.size() == 3) {
        button11->setVisible(true);
        label29->setText(l[0].Sj);
        if (l[0].Jg == "1") {
            button11->setBackgroundBmp("b1");
            label29->setTextColor(QColor(255, 0, 0));
        }
        button12->setVisible(true);
        label28->setText(l[1].Sj);
        if (l[1].Jg == "1") {
            button12->setBackgroundBmp("b1");
            label28->setTextColor(QColor(255, 0, 0));
        }
        button13->setVisible(true);
        label27->setText(l[2].Sj);
        if (l[2].Jg == "1") {
            button13->setBackgroundBmp("b1");
            label27->setTextColor(QColor(255, 0, 0));
        }
        button14->setVisible(false);
    } else {
        button11->setVisible(true);
        label29->setText(l[l.size()-4].Sj);
        if (l[l.size() - 4].Jg == "1") {
            button11->setBackgroundBmp("b1");
            label29->setTextColor(QColor(255, 0, 0));
        } else {
            button11->setBackgroundBmp("b2");
            label29->setTextColor(QColor(255, 255, 255));
        }
        button12->setVisible(true);
        label28->setText(l[l.size() - 3].Sj);
        if (l[l.size() - 3].Jg == "1") {
            button12->setBackgroundBmp("b1");
            label28->setTextColor(QColor(255, 0, 0));
        } else {
            button12->setBackgroundBmp("b2");
            label28->setTextColor(QColor(255, 255, 255));
        }
        button13->setVisible(true);
        label27->setText(l[l.size() - 2].Sj);
        if (l[l.size() - 2].Jg == "1") {
            button13->setBackgroundBmp("b1");
            label27->setTextColor(QColor(255, 0, 0));
        } else {
            button13->setBackgroundBmp("b2");
            label27->setTextColor(QColor(255, 255, 255));
        }
        button14->setVisible(true);
        label26->setText(l[l.size() - 1].Sj);
        if (l[l.size() - 1].Jg == "1") {
            button14->setBackgroundBmp("b1");
            label26->setTextColor(QColor(255, 0, 0));
        } else {
            button14->setBackgroundBmp("b2");
            label26->setTextColor(QColor(255, 255, 255));
        }
    }
}

void MainWindow::getjiaoyanshizhe()
{
    QString shijian=  QDateTime::currentDateTime().toString("HH:mm:ss");
    ll.clear();
    if (db1.isOpen()) {
        arr[0] = "成功";
        QString sql = QString("select * from jiaoyanshezhi where starttime>'%1' order by starttime").arg(shijian);
        QSqlQuery query(db1);
        query.exec(sql);
        while(query.next()) {
            QString starttime = query.value("starttime").toString();
            QString endtime = query.value("endtime").toString();
            ll.append(Ttime(starttime, endtime, QString("")));
        }

        if(ll.size() == 0) {
            ll.append(Ttime(QString("23:50"), QString("23:59"), QString("")));
        }

    } else {
        arr[0] = "失败";
    }
}

void MainWindow::onSetting()
{
    SettingDlg* dlg = new SettingDlg();
    dlg->setFocus();
    int result = dlg->exec();

    delete dlg;

    QSettings set(SettingDlg::ConfigFile, QSettings::IniFormat);
    bHasRFID = set.value("bHasRFID", "false").toBool();//切换到RFID

    switch(result) {
    default:
    case 0:
        break;
    case 1:
        //重启
        qApp->exit(777777);
        break;
    case -1:
//        onExit();
        resetData();//重置
        return;
    }

}

void MainWindow::closeDB()
{
    try {
        if (db1.isOpen()) {
            // 关闭数据库连接
            db1.close();
        } else {
            qDebug() << "Database is not open.";
        }
    }catch(const char *error) {
        qDebug() << "Caught exception: " << error;
    }
}

void MainWindow::onExit()
{
    closeDB();
    //    QProcess::startDetached("sudo shutdown -h now");
    QApplication* app;
    app->exit(0);
}

void MainWindow::openSerialport()
{
    QSettings set(SettingDlg::ConfigFile, QSettings::IniFormat);

    //检针机串口
    QString strJZCom = set.value("jz_com", "com1").toString();
    qDebug() << strJZCom;
    QString strJZBaudrate = set.value("jz_baudrate", "9600").toString();
    int jz_baudrate = strJZBaudrate.toInt();

    QString strMsg = "";
    jz_com = new QextSerialPort(strJZCom, QextSerialPort::Polling);
    comOk = jz_com->open(QIODevice::ReadWrite);
    if (comOk) {
        //清空缓冲区
        jz_com->flush();
        //设置波特率
        jz_com->setBaudRate((BaudRateType)jz_baudrate);
        //设置数据位
        jz_com->setDataBits((DataBitsType)8);
        //设置校验位
        jz_com->setParity(ParityType::PAR_NONE);
        //设置停止位
        jz_com->setStopBits(StopBitsType::STOP_1);
        jz_com->setFlowControl(FLOW_OFF);
        jz_com->setTimeout(10);
        jz_timerRead->start();
        set.setValue("jz_com", strJZCom);
        set.setValue("jz_baudrate", strJZBaudrate);

        strMsg = "1-";
    }

    //灵敏度串口
    QString strAccuracyCom = set.value("accuracy_com", "com2").toString();
    qDebug() << strAccuracyCom;
    QString strAccuracyBaudrate = set.value("accuracy_baudrate", "9600").toString();
    int accuracy_baudrate = strAccuracyBaudrate.toInt();

    accuracy_com = new QextSerialPort(strAccuracyCom, QextSerialPort::Polling);
    comOk = accuracy_com->open(QIODevice::ReadWrite);
    if (comOk) {
        //清空缓冲区
        accuracy_com->flush();
        //设置波特率
        accuracy_com->setBaudRate((BaudRateType)accuracy_baudrate);
        //设置数据位
        accuracy_com->setDataBits((DataBitsType)8);
        //设置校验位
        accuracy_com->setParity(ParityType::PAR_NONE);
        //设置停止位
        accuracy_com->setStopBits(StopBitsType::STOP_1);
        accuracy_com->setFlowControl(FLOW_OFF);
        accuracy_com->setTimeout(10);
        accuracy_timerRead->start();
        set.setValue("accuracy_com", strAccuracyCom);
        set.setValue("accuracy_baudrate", strAccuracyBaudrate);
        strMsg = strMsg + "2-";
    }

    // 扫码枪com配置
    QString strSaomaCom = set.value("saoma_com", "com3").toString();
    qDebug() << strSaomaCom;
    QString strSaomaBaudrate = set.value("saoma_baudrate", "9600").toString();
    int saoma_baudrate = strSaomaBaudrate.toInt();

    saoma_com = new QextSerialPort(strSaomaCom, QextSerialPort::Polling);
    comOk = saoma_com->open(QIODevice::ReadWrite);
    if (comOk) {
        //清空缓冲区
        saoma_com->flush();
        //设置波特率
        saoma_com->setBaudRate((BaudRateType)saoma_baudrate);
        //设置数据位
        saoma_com->setDataBits((DataBitsType)8);
        //设置校验位
        saoma_com->setParity(ParityType::PAR_NONE);
        //设置停止位
        saoma_com->setStopBits(StopBitsType::STOP_1);
        saoma_com->setFlowControl(FLOW_OFF);
        saoma_com->setTimeout(10);
        saoma_timerRead->start();
        set.setValue("saoma_com", strSaomaCom);
        set.setValue("saoma_baudrate", strSaomaBaudrate);

        strMsg = strMsg + "3";
    }

    mDingdan->setText(strMsg);
}

void MainWindow::closeSerialport()
{
    jz_timerRead->stop();
    jz_com->close();
    jz_com->deleteLater();

    accuracy_timerRead->stop();
    accuracy_com->close();
    accuracy_com->deleteLater();
    saoma_timerRead->stop();
    saoma_com->close();
    saoma_com->deleteLater();
    comOk = false;
}

//200ms读数据
void MainWindow::rfidtable_readData()
{
    if (!bHasRFID) {
        return;
    }

    try {
        if (db1.isOpen()) {
            // 第1步：从rfid_insert_list表读取当前时间之前3秒内的数据。
            // 获取当前时间
            QDateTime currentDateTime = QDateTime::currentDateTime();
            // 提取时间戳（以毫秒为单位）
            qint64 timeStamp = currentDateTime.toMSecsSinceEpoch();
            QString sql = QString("SELECT * FROM `rfid_insert_list` WHERE time_stamp >= (%1 - 5000) order by time_stamp desc LIMIT 3")
                    .arg(QString("%1").arg(timeStamp));
            QSqlQuery query(db1);
            query.exec(sql);
            while(query.next()) {
                // 在当前时间前3秒内，有1条记录
                UPC = query.value("upc").toString();
                mTiaoma->setText(QString(tr("条码:") + "%1").arg(UPC));

                if(setRfid.contains(query.value("upc").toString())) // 已经处理过了
                    continue;
                setRfid.insert(query.value("upc").toString());  //添加到set集合
                playWavFile(0);

                sql = QString("INSERT INTO `esm_md_chanliang_list`(`upc`,`sn`,`line`,`riqi`,`time_stamp`,`accuracy`) "
                              "VALUES ('%1','%2','%3','%4','%5','%6')")
                        .arg(UPC, mSn, mLinename, QDateTime::currentDateTime().toString("yyyy-MM-dd"),
                             QString("%1").arg(timeStamp), QString("%1").arg(accuracy));
                sqlexecute(sql, 0);
            }
        }
    } catch(const char *error) {
        qDebug() << "Caught exception: " << error;
    }
}

void MainWindow::jz_readData()
{
    if (jz_com->bytesAvailable() <= 0) {
        return;
    }

    QUIHelper::sleep(sleepTime);
    QByteArray data = jz_com->readAll();
    int dataLen = data.length();
    if (dataLen <= 0) {
        return;
    }

    QString buffer;
    buffer = QUIHelperData::byteArrayToHexStr(data); //16进制
    lastCombuffer = buffer;
    docommand_jz(buffer);
}

void MainWindow::accuracy_readData()
{
    if (accuracy_com->bytesAvailable() <= 0) {
        return;
    }

    QUIHelper::sleep(sleepTime);
    QByteArray data = accuracy_com->readAll();
    int dataLen = data.length();
    if (dataLen <= 0) {
        return;
    }

    QString buffer;
    buffer = QUIHelperData::byteArrayToHexStr(data); //16进制
    lastCombuffer = buffer;
    docommand_accuracy(buffer);

}

void MainWindow::saoma_readData()
{
    if (saoma_com->bytesAvailable() <= 0) {
        return;
    }

    QUIHelper::sleep(sleepTime);
    QByteArray data = saoma_com->readAll();
    int dataLen = data.length();
    if (dataLen <= 0) {
        return;
    }

    QString buffer;
    buffer = QUIHelperData::byteArrayToHexStr(data); //16进制
    lastCombuffer = buffer;
    docommand_saoma(buffer);

}

void MainWindow::docommand_jz(const QString& data)
{
    //无码不检针
    if (UPC.isEmpty())
        return;

    //    下位机回应运行状态
    //    com4 => com3
    //    MD-11客户端（上位机）=> 检针机（下位机）
    //    AA 19 0A 12 34 80 01 02 00 AB 3E
    //    80 -- 停止
    //    81 -- 运行
    //    01 -- 正常通过
    //    02 -- 误报
    //    03 -- 有针
    //    合格数=0102H，检出数=00ABH
    QStringList cmdlist = data.split("AA ");
    for (int i = 0; i < cmdlist.count(); i++) {
        //QString strB = "AA 19 0A 12 34 80 01 02 00 AB 3E";
        QString strB = cmdlist[i];
        if (strB.length() < 20) {
            continue;
        }
        QStringList list = strB.split(" ");
        if (list.length() <= 9) {
            continue;
        }

        if (list[0] == "01" || list[0] == "06" || list[0] == "10") {
            continue;
        }

        if (model == 0) {
            //正常
            if (list[4] == "80") {
                //mZt->setBackgroundBmp(QString("zt1"));
            } else if (list[4] == "81") {
                mZt->setBackgroundBmp(QString("zt2"));
            } else if (list[4] == "01") {
                if(!bHasRFID) {
                    doHege();
                }
            } else if (list[4] == "02") {
                //误报
                wubao++;
            } else if (list[4] == "03") {
                //断针
                if(bIs900N) {
                    //断针不退，直接记录--无复检和终检
                    doDuanzhen();
                } else {
                    //RFID或扫鞋舌标
                    model = 2;//第1次断针后进入复检;
                    mZhengchang->setText(tr("复检"), true);
                }

            }
        } else if (model == 1) {
            //暂停 XX
        } else if (model == 2) {
            if (list[4] == "01") {
                doHege();
            } else if (list[4] == "03") {
                model = 3;//第2次断针后进入复检
                mZhengchang->setText(tr("终检"), true);
            }

        } else if (model == 3) {
            //终检
            if (list[4] == "80") {
                //mZt->setBackgroundBmp(QString("zt1"));
            } else if (list[4] == "81") {
                mZt->setBackgroundBmp(QString("zt2"));
            } else if (list[4] == "01") {
                doHege();
            } else if (list[4] == "02") {
                //误报
                wubao++;
            } else if (list[4] == "03") {
                //第3次断针
                doDuanzhen();
            }
            mZhengchang->setText(tr("正常"), true);
//            fg1->setVisible(false);
//            fg3->setVisible(true);
        } else if (model == 4) {
            //校验
            if (list[4] == "80") {
                // mZt->setBackgroundBmp(QString("zt1"));
            } else if (list[4] == "81") {
                mZt->setBackgroundBmp(QString("zt2"));
            } else if (list[4] == "01") {
                //无针有光：漏报检块+1
                mJy21->setText(QString("%1").arg(mJy21->getText().toInt() + 1));
            } else if (list[4] == "02") {
                //有针无光：报警检棒+1
                mJy11->setText(QString("%1").arg(mJy11->getText().toInt() + 1));
            } else if (list[4] == "03") {
                //有针有光：报警检块+1
                mJy11->setText(QString("%1").arg(mJy11->getText().toInt() + 1));
            }
        }
    }
}

void MainWindow::doHege()
{
    //无码不检针
    if (UPC.isEmpty())
        return;

    mDingdan->setTextColor(QColor(255, 255, 255));
    mDingdan->setText(">>>>>PASS");

    QString uuid = QUuid::createUuid().toString();
    uuid = uuid.mid(1, uuid.length() - 2);
    uuid = uuid.replace("-", "");
    QString riqi = QDateTime::currentDateTime().toString("yyyy-MM-dd");
    QString shijian=  QDateTime::currentDateTime().toString("HH:mm:ss");
    QString po = "";
    // 获取当前时间
    QDateTime currentDateTime = QDateTime::currentDateTime();
    // 提取时间戳（以毫秒为单位）
    qint64 timeStamp = currentDateTime.toMSecsSinceEpoch();

    QSqlQuery query(db1);
    QString sql = QString("SELECT * FROM `esm_md_chanliang_list` where riqi=CURDATE() and upc='%1' ").arg(UPC);
    query.exec(sql);
    bool isfind = false;
    while(query.next()) {
        isfind = true;
        break;
    }

    if (isfind) {
        sql = QString("update esm_md_chanliang_list set type=0, time_stamp='%1', accuracy='%2' where riqi=CURDATE() and upc='%3' ")
                .arg(QString("%1").arg(timeStamp), QString("%1").arg(accuracy), UPC);
        sqlexecute(sql, 0);
    } else {
        sql = QString("INSERT INTO `esm_md_chanliang_list`(`upc`,`sn`,`line`,`riqi`,`time_stamp`,`accuracy`) "
                      "VALUES ('%1','%2','%3','%4','%5','%6')")
                .arg(UPC, mSn, mLinename, QDateTime::currentDateTime().toString("yyyy-MM-dd"),
                     QString("%1").arg(timeStamp), QString("%1").arg(accuracy));
        sqlexecute(sql, 0);
    }

    model = 0;
    mZhengchang->setbmpPath(QString("bt3"), QString("bt2"));
    mZhengchang->setText(tr("正常"), true);
    mDingdan->setTextColor(QColor(255, 255, 255));
    mDingdan->setText(">>>>>PASS");
//    fg1->setVisible(false);
//    fg3->setVisible(true);

}

void MainWindow::doDuanzhen()
{
    //无码不检针
    if (UPC.isEmpty())
        return;

    mDingdan->setText(">>>>>FAIL");
    mDingdan->setTextColor(QColor(255, 0, 0));

    QString uuid = QUuid::createUuid().toString();
    uuid = uuid.mid(1, uuid.length() - 2);
    uuid = uuid.replace("-", "");
    QString riqi = QDateTime::currentDateTime().toString("yyyy-MM-dd");
    QString shijian=  QDateTime::currentDateTime().toString("HH:mm:ss");
    QString po = "";
    // 获取当前时间
    QDateTime currentDateTime = QDateTime::currentDateTime();
    // 提取时间戳（以毫秒为单位）
    qint64 timeStamp = currentDateTime.toMSecsSinceEpoch();

    QSqlQuery query(db1);

    QString sql = QString("SELECT * FROM `duanzhen` where riqi=CURDATE() and upc='%1' ").arg(UPC);
    query.exec(sql);

    bool isfind = false;
    while(query.next()) {
        isfind = true;
        break;
    }

    if (isfind) {
        sql = QString("update duanzhen set shijian='%1', accuracy='%2' where riqi=CURDATE() and upc='%3' ")
                .arg(shijian, QString("%1").arg(accuracy), UPC);
        sqlexecute(sql, 0);
    } else {
        QString dy = QString("N");
        sql = QString("insert into duanzhen(id,po,tm,upc,dy,lyouzhen,fuyouzhen,jieguo,"
                              "shijian,riqi,sn,ryouzhen,accuracy) "
                              "values ('%1','%2','%3','%4','%5','%6', '%7', 1, "
                              "'%8', '%9', '%10', '%11', '%12') ")
                .arg(uuid, po, UPC, UPC, dy, QString("%1").arg(fujianzuo),QString("%1").arg(fujianzuo+fujianyou),
                     shijian, riqi, mSn, QString("%1").arg(fujianyou), QString("%1").arg(accuracy));
        sqlexecute(sql, 0);
    }

    sql = QString("SELECT * FROM `esm_md_chanliang_list` where riqi=CURDATE() and upc='%1' ").arg(UPC);
    query.exec(sql);
    isfind = false;
    while(query.next()) {
        isfind = true;
        break;
    }

    if (isfind) {
        sql = QString("update esm_md_chanliang_list set type=1, time_stamp='%1', accuracy='%2' where riqi=CURDATE() and upc='%3' ")
                .arg(QString("%1").arg(timeStamp), QString("%1").arg(accuracy), UPC);
        sqlexecute(sql, 0);
    } else {
        sql = QString("INSERT INTO `esm_md_chanliang_list`(`upc`,`sn`,`line`,`riqi`,`time_stamp`,`accuracy`,`type`) "
                      "VALUES ('%1','%2','%3','%4','%5','%6','%7')")
                .arg(UPC, mSn, mLinename, QDateTime::currentDateTime().toString("yyyy-MM-dd"),
                     QString("%1").arg(timeStamp), QString("%1").arg(accuracy), "1");
        sqlexecute(sql, 0);
    }

    model = 0;
    mZhengchang->setbmpPath(QString("bt3"), QString("bt2"));
    mZhengchang->setText(tr("正常"), true);
//    fg1->setVisible(false);
//    fg3->setVisible(true);

}

/*
* 上报传感器路数：
* 01234567890123456789
* AA 20 06 00 00 04 2B （04是第4路）

* 灵敏度上报指令：
* 01234567890123456789
* AA 21 06 00 00 0A F3 代表是level为10（0A）
*
* 合并数据帧：
* 01234567890123456789012345678901234567890
* AA 20 06 00 00 04 2B AA 21 06 00 00 0A F3    数据
* 01234567890123456789012345678901234567890
* AA 21 06 00 00 0A F3 AA 20 06 00 00 04 2B    数据
 */
void MainWindow::docommand_accuracy(const QString& data)
{
    try {
        if(data[0] != 'A' || data[1] != 'A') {
            return;
        }
        if(data.length() == 20 || data.length() >= 41) {
            int nIndex = data.length() == 20? 3: 34;
            int nDataIndex = data.length() == 20? 16: 37;
            if(data[nIndex] == '2' && data[nIndex + 1] == '1') {
                //灵敏度数据帧
                int temp_accuracy = data[nDataIndex].digitValue();
                if(data[nDataIndex] >= 'A') temp_accuracy = 10; //最大是10路
                if(accuracy != temp_accuracy) {
                    //更新灵敏度
                    accuracy = temp_accuracy;
                    mAccuracy->setText(QString("%1").arg(accuracy));
                }
            } else if(data[nIndex] == '2' && data[nIndex + 1] == '0') {
                // AA 20 06 00 00 04 2B  第4路
                if(model == 4) {
                    //当前的校正路数
                    int temp_lushu = data[nDataIndex].digitValue();
                    if(data[nDataIndex] >= 'A') temp_lushu = 10; //最大是10路
                    //更新路数
                    auto it = myMap.find(temp_lushu);  // 查找键为"temp_lushu"的元素
                    if (it != myMap.end()) {
                        //qDebug() << "Value: " << it.value();
                        temp_lushu = myMap.value(temp_lushu);
                    } else {
//                        qDebug() << "Key not found";
                    }
                    current_lushu = temp_lushu;
                    updateLushuList(current_lushu, true);
                }
            }
        }
    } catch(const char *error) {
        qDebug() << "Caught exception: " << error;
    }
}

void MainWindow::docommand_saoma(const QString& data)
{
    try {
        if(!data.isEmpty()) {
            QString pre_UPC = UPC;
            UPC = QUIHelperData::hexStrToByteArray(data);
            if(UPC == "NoRead") {
                UPC = "";
            }
            if (UPC.endsWith("\r\n")) {
                UPC.remove(UPC.length() - 2, 2);  // 去掉最后2个字符
            }
            if (UPC.endsWith("\n")) {
                UPC.remove(UPC.length() - 1, 1);  // 去掉最后一个字符
            }
            if (UPC.endsWith("\r")) {
                UPC.remove(UPC.length() - 1, 1);  // 去掉最后一个字符
            }
            //去掉前后{}
            if (UPC.startsWith("{") && UPC.endsWith("}")) {
                UPC = UPC.mid(1, UPC.length() - 2);
            }

            if(pre_UPC != UPC) {
                mDingdan->setText("");
                mTiaoma->setText(QString(tr("条码:") + "%1").arg(UPC));
            }
        }
    } catch(const char *error) {
        qDebug() << "Caught exception: " << error;
    }
}

//每秒都会刷新
void MainWindow::updateData()
{
    //刷新断针列表
    try {
        if (db1.isOpen()) {
            QString sql = QString("select upc, accuracy, substring(update_time, 11) as update_time, xray from duanzhen where sn='%1' "
                                  "and riqi= CURDATE() order by update_time DESC")
                    .arg(Start::getInstance().strSn);
            QSqlQuery query(db1);
            bool execOK = query.exec(sql);

            if (!execOK) {
                qDebug() << "Error executing query:" << query.lastError();
                return;  // 或其他错误处理
            }

            tableWidget2->clearContents();
            int num = 0;
            if (query.last()) {
                num = query.at() + 1;
            }

            query.first();//重新定位指针到结果集首位
            query.previous();//如果执行query.next来获取结果集中数据，要将指针移动到首位的上一位。

            tableWidget2->setRowCount(num);

            QFont font;
            font.setWeight(QFont::DemiBold);

            int i = 0;
            QList<QTableWidgetItem *> itemList;
            int xRayTobeConfirmNum = 0;
            chupan = 0;
            int Xrayjinshu = 0;         //Xray最终金属数
            while(query.next()) {
                chupan++;

                itemList.clear();
                itemList << new QTableWidgetItem(QString("%1").arg(i+1));

                QString upc = query.value("upc").toString();
                itemList << new QTableWidgetItem(upc);

                QString accuracy = query.value("accuracy").toString();
                itemList << new QTableWidgetItem(accuracy);

                QString update_time = query.value("update_time").toString().trimmed();
                itemList << new QTableWidgetItem(update_time);

                itemList << new QTableWidgetItem("NG");

                QString xray = query.value("xray").toString();
                if(!xray.isEmpty()) {
                    if(xray == '1'){
                        itemList << new QTableWidgetItem("Fail");
                        Xrayjinshu++;
                    } else {
                        itemList << new QTableWidgetItem("Pass");
                    }
                } else {
                    itemList << new QTableWidgetItem("");
                    xRayTobeConfirmNum++;
                }

                QColor bkColor = QColor(0, 0, 0);
                for (int j = 0; j < itemList.size(); j++) {
                    if(itemList[5]->text() == "Pass") {
                        //itemList[j]->setBackground(QColor(0, 255, 0)); // 设置背景颜色为绿色
                        //itemList[j]->setForeground(QColor(0, 0, 0));    // 前景是白色
                        itemList[j]->setForeground(QColor(0, 255, 0));    // 前景是绿色
                    } else if(itemList[5]->text() == "Fail") {
                        //itemList[j]->setBackground(QColor(255, 0, 0));  // 设置背景颜色为红色
                        //itemList[j]->setForeground(QColor(0, 0, 0));    // 前景是黑色
                        itemList[j]->setForeground(QColor(255, 0, 0));    // 前景是红色
                    } else {
                        //itemList[j]->setBackground(bkColor);
                        itemList[j]->setForeground(QColor(255, 255, 0));    // 前景是黄色
                    }
                    itemList[j]->setBackground(bkColor);
                    itemList[j]->setFont(font);
                    itemList[j]->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
                    itemList[j]->setFlags(itemList[j]->flags() & ~Qt::ItemIsEnabled & ~Qt::ItemIsSelectable);

                    tableWidget2->setItem(i, j, itemList[j]);
                }
                i++;
            }
            //初判金属数
            mChupan->setText(QString("%1").arg(chupan));
            //X-Ray待确认数
            mXrayTobeConfirm->setText(QString::number(xRayTobeConfirmNum));
            //X-Ray确认不合格数
            mXrayFail->setText(QString::number(Xrayjinshu));

            //补齐剩余的行
            int buyu = (12 - num % 12);
            tableWidget2->setRowCount(num + buyu);
            for (int i = num; i < num + buyu; i++) {
                for (int j = 0; j < 6; j++) {
                    QTableWidgetItem *item= new QTableWidgetItem("");
                    item->setBackground(QColor(0, 0, 0));
                    item->setFont(font);
                    item->setForeground(QColor(0, 0, 0));
                    item->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
                    item->setFlags(item->flags() & ~Qt::ItemIsEnabled & ~Qt::ItemIsSelectable);
                    tableWidget2->setItem(i, j, item);
                }
            }

            //
            // 合格数 + 金属数
            //SELECT SUM(CASE WHEN `type` = 0 THEN 1 ELSE 0 END) AS count_type_0, SUM(CASE WHEN `type` = 1 THEN 1 ELSE 0 END) AS count_type_1 FROM `esm_md_chanliang_list`;
            sql = QString("SELECT SUM(CASE WHEN `type` = 0 THEN 1 ELSE 0 END) AS hege, "
                                  "SUM(CASE WHEN `type` = 1 THEN 1 ELSE 0 END) AS chupan "
                                  "FROM `esm_md_chanliang_list` where riqi=CURDATE()");
            query.exec(sql);
            while(query.next()) {
                hege = query.value("hege").toInt();
                chupan = query.value("chupan").toInt();//chupan已经更新了
                break;
            }

            mHgs->setText(QString::number(hege));
            mChupan->setText(QString::number(chupan));
            zongshu = hege + chupan;

            sql = QString("update hostorydata set chupan=%1, zongshu=%2 where riqi=CURDATE() ")
                    .arg(QString("%1").arg(chupan), QString("%1").arg(zongshu));
            sqlexecute(sql, 0);
            sendData(Jzcommand::getczcmd(hege, chupan), true);//写检针机没啥意义

            if(bHasKanban) m_threadSocket.setContextString("$" + QString::number(hege) + "#" + QString::number(chupan) + "\r\n");
        }
    } catch(const char *error) {
        qDebug() << "Caught exception: " << error;
    }
}

//校正列表
void MainWindow::getData23()
{
    try {
        QFont font;
        font.setWeight(QFont::DemiBold);
        tableWidget3->setRowCount(sensors);

        QList<QTableWidgetItem *> itemList;
        for(int i = 0; i < sensors; i++) {
            itemList.clear();
            itemList << new QTableWidgetItem(QString("%1").arg(QString::number(i+1)));
            itemList << new QTableWidgetItem(QString("%1").arg(QString::number(accuracy)));
            itemList << new QTableWidgetItem("");
            itemList << new QTableWidgetItem("");
            //qDebug() << itemList[0] << itemList[1] << itemList[2] << itemList[3];
            QColor bkColor = QColor(0, 0, 0);
            for (int j = 0; j < itemList.size(); j++) {
                itemList[j]->setBackground(bkColor);
                itemList[j]->setFont(font);
                itemList[j]->setForeground(QColor(255, 255, 0));
                itemList[j]->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
                itemList[j]->setFlags(itemList[j]->flags() & ~Qt::ItemIsEnabled & ~Qt::ItemIsSelectable);
                tableWidget3->setItem(i, j, itemList[j]);
            }
        }
        tableWidget3->show();   //一定要加，否则不显示内容
    } catch(const char *error) {
        qDebug() << "Caught exception: " << error;
    }
}

void MainWindow::updateLushuList(int nLushu, bool bRet)
{
    try {
        //更新路数表，在校正模式下
        if(model != 4) {
            return;
        }
        //tableWidget3从0开始
        nLushu--;
        if(nLushu >= 0 && nLushu < sensors) {
            //更新列表
            if(bRet) {
                QString newContent = QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss");
                //qDebug() << newContent;
                QTableWidgetItem *newItem = new QTableWidgetItem(newContent);
                tableWidget3->setItem(nLushu, 2, newItem);  //时间
                newContent = "OK"; // 这是你想设置的新内容
                newItem = new QTableWidgetItem(newContent);
                tableWidget3->setItem(nLushu, 3, newItem);  //状态
                //调整颜色
                QTableWidgetItem *item = tableWidget3->item(pre_lushu, 3);
                if(item) {
                    if(item->text() != "") {
                        for(int i = 0; i < 4; i++) {
                            //恢复前一行颜色
                            item->setForeground(QColor(0, 0, 0));
                            item->setBackground(QColor(0, 154, 97));
                            item->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
                            item = tableWidget3->item(pre_lushu, i);
                        }
                    }
                }

                item = tableWidget3->item(nLushu, 0);
                if(item) {
                    for(int j = 1; j <= 4; j++) {
                        // 设置当前行背景颜色
                        item->setForeground(QColor(255, 255, 0));
                        item->setBackground(QColor(0, 255, 0));
                        item->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
                        item = tableWidget3->item(nLushu, j);
                    }
                }
                tableWidget3->show();
                pre_lushu = nLushu;

                //更新数据库jiaoyandetails
                QString sql = QString("update jiaoyandetails set `status` ='%1', accuracy = %2  where passageway ='%3' and guid='%4';").
                        arg("0", QString::number(accuracy), QString::number(nLushu+1), JZ_UUID);
                sqlexecute(sql, 0);
            }
        }
    } catch(const char *error) {
        qDebug() << "Caught exception: " << error;
    }
}

void MainWindow::sendData(const QString& data, bool isHex)
{
    if (jz_com == 0 || !jz_com->isOpen()) {
        return;
    }

    QByteArray buffer;
    if (isHex) {
        buffer = QUIHelperData::hexStrToByteArray(data);
    } else {
        buffer = QUIHelperData::asciiStrToByteArray(data);
    }

    jz_com->write(buffer);

}

void MainWindow::initDB()
{
    QString myconnection = "myconnection_" + QDateTime::currentDateTime().toString("yyyyMMddHHmmss");
    db1 = QSqlDatabase::addDatabase("QODBC", myconnection);
    db1.setDatabaseName("jzdb2");//
    bool ok = db1.open();
    if (ok){
        qDebug()<<"jzdb2::success";
    } else {
        qDebug()<<"jzdb2::failed";
    }

}

void MainWindow::saveLinesn(const QString& Linename, const QString& Sn)
{
    QString uuid = QUuid::createUuid().toString();
    uuid = uuid.mid(1, uuid.length() - 2);
    uuid = uuid.replace("-", "");
    QString sql = QString("INSERT INTO `device` \(`id`, `sn`, `factory`, `loudong`, `pname`, `riqi`, `model`, `modeltext`, `mbpph`, `mbcl`, `jiepai`, `renshu`, `taitou`, `zt`, `k1`, `j1`, `k2`, `j2`, `k3`, `j3`, `user`, `k1_2`, `j1_2`, `k2_2`, `j2_2`, `k1_3`, `j1_3`, `k2_3`, `j2_3`\) VALUES \('%1', '%2', NULL, NULL, '%3', '2021-12-07', NULL, NULL, 18, 28800, 60, 200, '生产实时数据', 0, '08:00', '11:30', '12:30', '17:00', '00:00', '00:00', NULL, '00:00', '00:00', '00:00', '00:00', '00:00', '00:00', '00:00', '00:00'\)").arg(uuid, Sn, Linename);

    if (db1.isOpen()) {
        QSqlQuery query(db1);
        query.exec(sql);
    }

}

//type 0 -- db1  1-- db2
void MainWindow::sqlexecute(const QString& sql, int type)
{
    if (type == 0 && db1.isOpen()) {
        QSqlQuery query(db1);
        query.exec(sql);
    }
}

void MainWindow::udateuibydb()
{
    updateData();//刷断针列表;并更新hege chupan

    checktime++;
    if (checktime > 60) {
        //1 分钟检测1次
        popJzMsg();//在时间范围内检测，弹出校正提示框
        checktime = 0;
    }
}

void MainWindow::popJzMsg()
{
    QString shijian = QDateTime::currentDateTime().toString("HH:mm");
    if (ll.size() > 0 && shijian > ll[0].stime && shijian < ll[0].etime && model!= 4) {
        MsgDlg* dlg = new MsgDlg();
        dlg->setMsg(tr("校验提示信息"), tr("校验时间到了\n请及时校验!"));
        dlg->setFocus();
        int result = dlg->exec();
        delete dlg;
        switch(result) {
        case 1:
            break;
        }
    }

}

//清空数据-duanzhen esm_md_chanliang_list hostorydata
void MainWindow::resetData() {
    QString sql = QString("update hostorydata set hege=0, zongshu=0, jinshu=0 where sn='%1' and riqi='%2'")
            .arg( mSn,QDateTime::currentDateTime().toString("yyyy-MM-dd"));
    sqlexecute(sql, 0);
    sqlexecute("TRUNCATE TABLE duanzhen", 0);
    sqlexecute("TRUNCATE TABLE esm_md_chanliang_list", 0);

    setRfid.clear();
    hege = 0;
    chupan = 0;
    zongshu = hege + chupan;
    sendData(Jzcommand::getczcmd(hege, chupan), true);

    mChupan->setText("0");
    mXrayTobeConfirm->setText("0");
    mHgs->setText("0");
    mXrayFail->setText("0");
    mDingdan->setText("");

}


